package com.nulldev.util.VariableAPI.util.strings;

import java.util.List;

import com.nulldev.util.VariableAPI.ArrayUtils;
import com.nulldev.util.VariableAPI.StringsUtil;

public class StringUtilFormatter {

	@SuppressWarnings("unchecked")
	private static <T> T getFromList(final List<Object> objects, final Class<T> cls) {
		for (int i = 0; i < objects.size(); i++) {
			final Object obj = objects.get(i);
			if (cls.isInstance(obj)) {
				objects.remove(i);
				return (T) obj;
			}
		}
		return null;
	}

	public static String format(final String str, final Object... objects) {
		if (str == null || str.isEmpty() || StringsUtil.isBlank(str))
			return str;
		if (objects == null || objects.length == 0)
			return str;
		final StringBuilder out = new StringBuilder(str);
		final List<Object> data = ArrayUtils.toArrayListFast(objects);
		{
			int string_idx = -1;
			while ((string_idx = out.indexOf("%s")) > -1) {
				final String s = getFromList(data, String.class);
				if (s == null)
					break;
				out.replace(string_idx, string_idx + 2, s);
			}
		}
		{
			int char_idx = -1;
			while ((char_idx = out.indexOf("%c")) > -1) {
				final char s = getFromList(data, char.class);
				out.replace(char_idx, char_idx + 2, String.valueOf(s));
			}
		}
		{
			int int_idx = -1;
			while ((int_idx = out.indexOf("%i")) > -1) {
				final int s = getFromList(data, int.class);
				out.replace(int_idx, int_idx + 2, String.valueOf(s));
			}
		}
		{
			int long_idx = -1;
			while ((long_idx = out.indexOf("%l")) > -1) {
				final long s = getFromList(data, long.class);
				out.replace(long_idx, long_idx + 2, String.valueOf(s));
			}
		}
		{
			int double_idx = -1;
			while ((double_idx = out.indexOf("%d")) > -1) {
				final double s = getFromList(data, double.class);
				out.replace(double_idx, double_idx + 2, String.valueOf(s));
			}
		}
		{
			int float_idx = -1;
			while ((float_idx = out.indexOf("%f")) > -1) {
				final float s = getFromList(data, float.class);
				out.replace(float_idx, float_idx + 2, String.valueOf(s));
			}
		}
		return out.toString();
	}
}
